using System;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;

namespace CPlatePrintSys.Annotation.Controls
{
    public class TextEditAdorner : Adorner
    {
        public Rect EditRect { get; set; } // 编辑区域（屏幕坐标）
        public double HandleSize { get; set; } = 12; // 拖拽点大小
        public bool ShowHandles { get; set; } = true;
        public bool ShowRotateHandle { get; set; } = true;
        public Brush FrameBrush { get; set; } = Brushes.Gray;
        public Pen FramePen { get; set; }
        public Brush HandleFill { get; set; } = Brushes.White;
        public Pen HandlePen { get; set; } = new Pen(Brushes.DeepSkyBlue, 2);
        public Brush RotateFill { get; set; } = Brushes.White;
        public Pen RotatePen { get; set; } = new Pen(Brushes.Black, 1);
        public bool IsSelected { get; set; } = true; // 可扩展
        
        /// <summary>
        /// 编辑框的旋转角度（弧度）
        /// </summary>
        public double RotationAngle { get; set; } = 0.0;

        /// <summary>
        /// 旋转中心点（屏幕坐标）
        /// </summary>
        public Point RotationCenter { get; set; } = new Point(0, 0);

        /// <summary>
        /// 获取旋转图标的边界矩形（屏幕坐标）
        /// </summary>
        public Rect RotateHandleBounds
        {
            get
            {
                if (EditRect.Width < 1 || EditRect.Height < 1) return Rect.Empty;
                
                double hs = HandleSize * 2;
                var topRight = new Point(EditRect.Right, EditRect.Top);
                var rotateCenter = new Point(topRight.X + hs * 0.5, topRight.Y - hs * 1.5);
                
                // 根据实际绘制的旋转图标大小返回边界
                double iconSize = hs * 0.8; // 与绘制中的 arrowSize 一致
                return new Rect(rotateCenter.X - iconSize/2, rotateCenter.Y - iconSize/2, iconSize, iconSize);
            }
        }

        public TextEditAdorner(UIElement adornedElement) : base(adornedElement)
        {
            FramePen = new Pen(FrameBrush, 1.5) { DashStyle = DashStyles.Dash };
            IsHitTestVisible = false; // 只做显示，命中检测在控件层处理
        }

        protected override void OnRender(DrawingContext dc)
        {
            if (EditRect.Width < 1 || EditRect.Height < 1) return;
            
            // 使用传入的旋转中心点
            dc.PushTransform(new RotateTransform(RotationAngle * 180 / Math.PI, RotationCenter.X, RotationCenter.Y));
            
            // 1. 外围虚线框
            dc.DrawRectangle(null, FramePen, EditRect);

            if (ShowHandles)
            {
                // 2. 8个2D正方形 - 保持与文字0度时一致的形状
                double hs = HandleSize;
                var pts = new Point[] {
                    new Point(EditRect.Left, EditRect.Top), // 左上
                    new Point(EditRect.Left + EditRect.Width/2, EditRect.Top), // 上中
                    new Point(EditRect.Right, EditRect.Top), // 右上
                    new Point(EditRect.Right, EditRect.Top + EditRect.Height/2), // 右中
                    new Point(EditRect.Right, EditRect.Bottom), // 右下
                    new Point(EditRect.Left + EditRect.Width/2, EditRect.Bottom), // 下中
                    new Point(EditRect.Left, EditRect.Bottom), // 左下
                    new Point(EditRect.Left, EditRect.Top + EditRect.Height/2), // 左中
                };
                Pen boxPen = IsSelected ? new Pen(Brushes.DeepSkyBlue, 2) : new Pen(Brushes.Gray, 2);
                foreach(var pt in pts)
                {
                    dc.DrawRectangle(HandleFill, boxPen, new Rect(pt.X - hs/2, pt.Y - hs/2, hs, hs));
                }
            }
            
            if (ShowRotateHandle)
            {
                // 3. 旋转手柄 - 使用三角形+圆弧组合
                double hs = HandleSize * 2;
                var topRight = new Point(EditRect.Right, EditRect.Top);
                var rotateCenter = new Point(topRight.X + hs * 0.5, topRight.Y - hs * 1.5);
                
                // 绘制旋转图标
                var arrowSize = hs * 0.8;
                var arrowCenter = rotateCenter;
                
                // 创建旋转图标路径
                var geo = new StreamGeometry();
                using (var ctx = geo.Open())
                {
                    // 绘制旋转图标 - 根据参考图设计
                    double triangleSize = arrowSize * 0.4; // 三角形大小
                    
                    // 圆弧参数
                    double radius = arrowSize * 0.6;
                    double startAngle = 0;  // 从右上开始
                    double endAngle = -Math.PI * 0.5;   // 到左下结束（逆时针）
                    
                    // 绘制圆弧
                    var startPoint = new Point(
                        arrowCenter.X + radius * Math.Cos(startAngle),
                        arrowCenter.Y + radius * Math.Sin(startAngle)
                    );
                    var endPoint = new Point(
                        arrowCenter.X + radius * Math.Cos(endAngle),
                        arrowCenter.Y + radius * Math.Sin(endAngle)
                    );
                    
                    ctx.BeginFigure(startPoint, false, false);
                    ctx.ArcTo(endPoint, new Size(radius, radius), 0, true, SweepDirection.Counterclockwise, true, false);


                    // 圆弧的切线方向：沿着圆弧的切线方向）
                    double triangleDirection = endAngle + Math.PI / 2;

                    var arrowSide1 = new Point(
                     endPoint.X - triangleSize * Math.Cos(triangleDirection + Math.PI / 3),
                     endPoint.Y - triangleSize * Math.Sin(triangleDirection + Math.PI / 3)
                    );

                    var arrowSide2 = new Point(
                        endPoint.X + triangleSize * Math.Cos(triangleDirection - Math.PI / 6),
                        endPoint.Y + triangleSize * Math.Sin(triangleDirection - Math.PI / 6)
                    );

                    // 绘制连接线（从圆弧终点到第一条边终点）
                    ctx.BeginFigure(endPoint, false, false);
                    ctx.LineTo(arrowSide1, true, true);

                    // 绘制连接线（从圆弧终点到第二条边终点）
                    ctx.BeginFigure(endPoint, false, false);
                    ctx.LineTo(arrowSide2, true, true);
                }
                
                // 绘制白色旋转图标
                dc.DrawGeometry(Brushes.White, new Pen(Brushes.White, 2), geo);
            }
            
            // 恢复变换状态 - 移到这里，确保旋转手柄也被旋转
            dc.Pop();
        }
    }


    // 专门用于显示文本编辑框的Adorner
    public class TextEditBoxAdorner : Adorner
    {
        private readonly System.Windows.Controls.TextBox _textBox;
        private readonly Rect _position;

        public TextEditBoxAdorner(UIElement adornedElement, System.Windows.Controls.TextBox textBox, Rect position)
            : base(adornedElement)
        {
            _textBox = textBox;
            _position = position;

            // 将TextBox添加到Adorner的视觉树中
            AddVisualChild(_textBox);
            AddLogicalChild(_textBox);
        }

        protected override int VisualChildrenCount => 1;

        protected override Visual GetVisualChild(int index)
        {
            if (index == 0) return _textBox;
            throw new ArgumentOutOfRangeException();
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            // 将TextBox放置在指定位置
            _textBox.Arrange(_position);
            return finalSize;
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            // 不需要额外的绘制，只需要显示TextBox
        }
    }

} 